<?php

namespace app\http;
use app\common\model\Brand;
use app\common\model\Company;
use app\common\model\Compute;
use app\common\model\ComputeDetail;
use app\common\model\Dose;
use app\common\model\Meal;
use app\common\model\Menu;
use app\common\model\Notice;
use app\common\model\Offer;
use app\common\model\OfferDetail;
use app\common\model\Order;
use app\common\model\Project;
use app\common\model\ProjectLog;
use app\common\model\Quantify;
use app\common\model\Quest;
use app\common\model\Send;
use app\common\model\Spec;
use app\common\model\Type;
use app\common\model\User;
use think\facade\Config;
//require_once '/vendor/autoload.php';
// 导入要请求接口对应的Request类
// 导入可选配置类
use think\worker\Server;
use Workerman\Lib\Timer;

class Worker extends Server {
	//protected $processes = 4;
	protected $socket = 'websocket://0.0.0.0:2003'; //正式
	//protected $socket = 'tcp://0.0.0.0:2008'; //测试
	/**
	 * 每个进程启动
	 * @param $worker
	 */
	public function onWorkerStart($worker) {
		Timer::add(1, array($this, 'quest'));
		Timer::add(1, array($this, 'compute'));
		Timer::add(10, array($this, 'project_log'));
		//Timer::add(10, array($this, 'send2'));
		// Timer::add(10, function () use ($worker) {
		// 	//添加心跳
		// 	foreach ($worker->connections as $connection) {
		// 		echo "connection-id = {$connection->id}\n";
		// 		$connection->send(1);
		// 	}
		// });

	}
	public function compute() {
		echo '[定量计算]--开始运行';
		echo "\r\n";
		$week = date('w');
		if ($week == 0) {
			$week = 7;
		}
		$config = Config::get('site.site');

		if ($week == $config['week']) {

			$order_list = Order::where('status', 0)->select();
			$meal_list = [];
			$type_list = [];
			foreach ($order_list as $order_key => $order_value) {
				$dose_list = Dose::where('order_id', $order_value['id'])->select();
				foreach ($dose_list as $dose_key => $dose_value) {

					foreach ($dose_value['detail'] as $detail_key => $detail_value) {

						$meal_list[] = [
							'meal_id' => $detail_value['meal_id'],
							'num' => $detail_value['num'],
							'school_id' => $order_value['school_id'],
							'order_id' => $order_value['id'],
							'dose_id' => $dose_value['id'],
							'tag' => $dose_value['tag'],
						];
					}

					foreach ($dose_value['detail2'] as $detail2_key => $detail2_value) {
						if ($detail2_value['brand_id'] == 22 && $detail2_value['spec_id'] == 214) {
							$detail2_num = round($detail2_value['num'] / 500, 2);
							$detail2_spec_id = 4;
							$detail2_brand_id = 3;
						} else {
							$detail2_num = $detail2_value['num'];
							$detail2_spec_id = $detail2_value['spec_id'];
							$detail2_brand_id = $detail2_value['brand_id'];
						}
						$type_list[] = [
							'type_id' => $detail2_value['type_id'],
							'spec_id' => $detail2_spec_id,
							'brand_id' => $detail2_brand_id,
							'num' => $detail2_num,
							'school_id' => $order_value['school_id'],
							'order_id' => $order_value['id'],
							'dose_id' => $dose_value['id'],
						];
					}

				}
				Order::where('id', $order_value['id'])->update(['status' => 1]);
			}

			$menu_list = [];
			if (count($order_list) > 0) {

				foreach ($meal_list as $meal_key => $meal_value) {

					$meal = Meal::where('id', $meal_value['meal_id'])->findOrEmpty();
					if (!$meal->isEmpty()) {
						foreach ($meal['detail'] as $meal_detail_key => $meal_detail_value) {
							$menu_list[] = $meal_detail_value['menu_id'];
							$menu = Menu::where('id', $meal_detail_value['menu_id'])->findOrEmpty();
							if (!$menu->isEmpty()) {
								foreach ($menu['detail'] as $menu_detail_key => $menu_detail_value) {
									if ($meal_value['num'] == '') {
										$meal_value['num'] = 0;
									}
									if ($meal_value['tag'] == 1) {
										$meal_value['num'] = 1;
									}

									if ($menu_detail_value['num'] == '') {
										$menu_detail_value['num'] = 0;
									}
									if ($menu_detail_value['brand_id'] == 22 && $menu_detail_value['spec_id'] == 214) {
										$menu_detail_num = round(($meal_value['num'] * $menu_detail_value['num']) / 500, 2);
										$menu_detail_spec_id = 4;
										$menu_detail_brand_id = 3;

									} else {
										$menu_detail_num = round($meal_value['num'] * $menu_detail_value['num'], 2);
										$menu_detail_spec_id = $menu_detail_value['spec_id'];
										$menu_detail_brand_id = $menu_detail_value['brand_id'];
									}

									$type_list[] = [
										'type_id' => $menu_detail_value['type_id'],
										'num' => $menu_detail_num,
										'spec_id' => $menu_detail_spec_id,
										'brand_id' => $menu_detail_brand_id,
										'school_id' => $meal_value['school_id'],
										'order_id' => $meal_value['order_id'],
										'dose_id' => $meal_value['dose_id'],
									];
								}
							}
						}
					}
				}

				$type_list2 = $this->array_do($type_list);

				$type_list3 = $this->array_do2($type_list);

				$start = date('Y-m-d', strtotime('next monday'));
				$end = date('Y-m-d', strtotime($start . '+ 6 days'));
				$quantify = Quantify::create(['name' => $start . '-' . $end . '计算结果']);
				foreach ($type_list2 as $key => $value) {
					$type = Type::where('id', $value['type_id'])->findOrEmpty();
					if (!$type->isEmpty()) {
						$compute_data = [
							'quantify_id' => $quantify->id,
							'parent_id' => $type['parent_id'],
							'type_id' => $value['type_id'],
							'spec_id' => $value['spec_id'],
							'brand_id' => $value['brand_id'],
							'code' => date('YmdHis') . rand(00000, 99999),
							'all_num' => $value['num'],
						];
						$compute = Compute::create($compute_data);
						foreach ($type_list3 as $tk => $tv) {

							$compute_detail_data = [
								'user_id' => 0,
								'compute_id' => $compute->id,
								'order_id' => $tv['order_id'],
								'school_id' => $tv['school_id'],
								'type_id' => $tv['type_id'],
								'spec_id' => $tv['spec_id'],
								'brand_id' => $tv['brand_id'],
								'num' => $tv['num'],
								'dose_id' => $tv['dose_id'],
							];
							$compute_detail = ComputeDetail::create($compute_detail_data);
						}
					}
				}
			}
		}

	}
	public function project_log() {
		echo '[生成配送单]--开始运行';
		echo "\r\n";
		$list = ProjectLog::where('status', 2)->where('tag', 0)->select();
		foreach ($list as $k => $v) {
			$this->send($v['id']);
			ProjectLog::where('id', $v['id'])->update(['tag' => 1]);
		}

	}
	public function send2() {
		echo '[合并配送单]--开始运行';
		echo "\r\n";
		$send_list = Send::whereDay('create_time')->where('type', 0)->select();
		foreach ($send_list as $k => $v) {
			$data = Send::where('id', '=', $v['id'])->find()->toArray();

			$list = Send::where('school_id', $data['school_id'])->where('send_time', strtotime($data['send_time']))->select()->toArray();
			$data['money'] = array_sum(array_column($list, 'money'));
			$data['detail'] = array_column($list, 'detail');
			$result = [];

			// 遍历原始三维数组
			foreach ($data['detail'] as $a) {
				foreach ($a as $b) {
					//将第三层的数组添加到二维数组中
					$result[] = $b;
				}
			}
			$data['detail'] = $result;
			$data['type'] = 1;
			$ids = array_column($list, 'id');
			unset($data['id'], $data['create_time'], $data['update_time'], $data['delete_time']);
			Send::create($data);
			Send::destroy(static function ($query) use ($ids) {
				$query->whereIn('id', $ids);
			});

		}

		$offer_list = OfferDetail::whereDay('create_time')->where('type', 0)->select();
		foreach ($offer_list as $k => $v) {
			$data = OfferDetail::where('id', '=', $v['id'])->find()->toArray();

			$list = OfferDetail::where('school_id', $data['school_id'])->where('send_time', strtotime($data['send_time']))->select()->toArray();
			$data['money'] = array_sum(array_column($list, 'money'));
			$data['detail'] = array_column($list, 'detail');
			$result = [];

			// 遍历原始三维数组
			foreach ($data['detail'] as $a) {
				foreach ($a as $b) {
					//将第三层的数组添加到二维数组中
					$result[] = $b;
				}
			}
			$data['detail'] = $result;
			$data['type'] = 1;
			$ids = array_column($list, 'id');
			unset($data['id'], $data['create_time'], $data['update_time'], $data['delete_time']);
			OfferDetail::create($data);
			OfferDetail::destroy(static function ($query) use ($ids) {
				$query->whereIn('id', $ids);
			});

		}
	}
	public function send($project_log_id) {

		$config = Config::get('site.site');

		$project_log = ProjectLog::where('id', $project_log_id)->findOrEmpty();
		if (!$project_log->isEmpty()) {
			$detail = [];
			$detail0 = [];
			$offer = [];
			//$dose_id_list = [];
			foreach ($project_log['detail'] as $key => $value) {

				$compute_detail_list = ComputeDetail::where('compute_id', $value['compute_id'])->select()->toArray();
				$dose_id_list = array_column($compute_detail_list, 'dose_id');
				$type_id_list = ['1281', '555', '1073', '557'];
				$type = Type::where('name', $value['name'])->where('tag', 1)->find();
				if (in_array($type['id'], $type_id_list)) {
					$detail0[] = [
						'type_id' => Type::where('name', $value['name'])->where('tag', 1)->value('id'),
						'spec_id' => Spec::where('name', $value['spec'])->value('id'),
						'brand_id' => Brand::where('name', $value['brand'])->value('id'),

						'price' => $value['money'],
						'shou_num' => 0,
						'wei_num' => 0,
						'avg_price' => 0,

						'status' => 0,
						'beizhu' => '',
						//'school_id' => $school_id,

					];
				} else {
					$detail[] = [
						'type_id' => Type::where('name', $value['name'])->where('tag', 1)->value('id'),
						'spec_id' => Spec::where('name', $value['spec'])->value('id'),
						'brand_id' => Brand::where('name', $value['brand'])->value('id'),

						'price' => $value['money'],
						'shou_num' => 0,
						'wei_num' => 0,
						'avg_price' => 0,

						'status' => 0,
						'beizhu' => '',
						//'school_id' => $school_id,

					];
				}

				$price = round($value['money'] + ($value['money'] * ($config['price'] / 100)), 2);
				$offer[] = [
					'type_id' => Type::where('name', $value['name'])->where('tag', 1)->value('id'),
					'spec_id' => Spec::where('name', $value['spec'])->value('id'),
					'brand_id' => Brand::where('name', $value['brand'])->value('id'),

					'price' => $price,

					'status' => 0,
					//'school_id' => $school_id,

				];

				//}

			}

			$dose_list = Dose::whereIn('id', $dose_id_list)->select()->toArray();
			$offer_detail_id = [];
			$school_id = [];
			foreach ($dose_list as $dose_key => $dose_value) {
				ComputeDetail::where('dose_id', $dose_value['id'])->update(['user_id' => $project_log['user_id']]);
				$meal_list = [];
				$type_list = [];
				foreach ($dose_value['detail'] as $detail_key => $detail_value) {

					$meal_list[] = [
						'meal_id' => $detail_value['meal_id'],
						'num' => $detail_value['num'],
						'dose_id' => $dose_value['id'],
						'tag' => $dose_value['tag'],
					];
				}

				foreach ($dose_value['detail2'] as $detail2_key => $detail2_value) {
					if ($detail2_value['brand_id'] == 22 && $detail2_value['spec_id'] == 214) {
						$detail2_num = round($detail2_value['num'] / 500, 2);
						$detail2_spec_id = 4;
						$detail2_brand_id = 3;
					} else {
						$detail2_num = $detail2_value['num'];
						$detail2_spec_id = $detail2_value['spec_id'];
						$detail2_brand_id = $detail2_value['brand_id'];
					}
					$type_list[] = [
						'type_id' => $detail2_value['type_id'],
						'spec_id' => $detail2_spec_id,
						'brand_id' => $detail2_brand_id,
						'num' => $detail2_num,
						'beizhu' => $detail2_value['beizhu'] ?? '',
						'dose_id' => $dose_value['id'],
					];
				}
				foreach ($meal_list as $meal_key => $meal_value) {

					$meal = Meal::where('id', $meal_value['meal_id'])->findOrEmpty();
					if (!$meal->isEmpty()) {
						foreach ($meal['detail'] as $meal_detail_key => $meal_detail_value) {
							$menu_list[] = $meal_detail_value['menu_id'];
							$menu = Menu::where('id', $meal_detail_value['menu_id'])->findOrEmpty();
							if (!$menu->isEmpty()) {
								foreach ($menu['detail'] as $menu_detail_key => $menu_detail_value) {
									if ($meal_value['num'] == '') {
										$meal_value['num'] = 0;
									}
									if ($meal_value['tag'] == 1) {
										$meal_value['num'] = 1;
									}
									if ($menu_detail_value['num'] == '') {
										$menu_detail_value['num'] = 0;
									}
									if (isset($menu_detail_value['beizhu']) && $menu_detail_value['beizhu'] != '') {
										$beizhu = $menu_detail_value['beizhu'];
									} else {
										$beizhu = '';
									}
									if ($menu_detail_value['brand_id'] == 22 && $menu_detail_value['spec_id'] == 214) {
										$menu_detail_num = round($menu_detail_value['num'] / 500, 2);
										$menu_detail_spec_id = 4;
										$menu_detail_brand_id = 3;
									} else {
										$menu_detail_num = $menu_detail_value['num'];
										$menu_detail_spec_id = $menu_detail_value['spec_id'];
										$menu_detail_brand_id = $menu_detail_value['brand_id'];
									}
									$type_list[] = [
										'type_id' => $menu_detail_value['type_id'],
										'num' => $meal_value['num'] * $menu_detail_num,
										'spec_id' => $menu_detail_spec_id,
										'brand_id' => $menu_detail_brand_id,
										'beizhu' => $beizhu,
										'dose_id' => $meal_value['dose_id'],
									];
								}
							}
						}
					}
				}

				$send_detail = $this->array_do3($detail, $type_list);
				foreach ($send_detail as $dk => $dv) {
					$send_detail[$dk]['money'] = round($dv['price'] * $dv['num'], 2);
				}
				$send_detail = $this->array_do($send_detail);

				$send_detail0 = $this->array_do3($detail0, $type_list);
				foreach ($send_detail0 as $dk => $dv) {
					$send_detail0[$dk]['money'] = round($dv['price'] * $dv['num'], 2);
				}
				$send_detail0 = $this->array_do($send_detail0);

				$offer_details = $this->array_do3($offer, $type_list);
				foreach ($offer_details as $ok => $ov) {
					$offer_details[$ok]['money'] = round($ov['price'] * $ov['num'], 2);
				}
				$offer_details = $this->array_do($offer_details);

				if (!empty($send_detail)) {

					$find_send = Send::where('school_id', $dose_value['school_id'])->where('send_time', strtotime($dose_value['week']))->where('user_id', $project_log['user_id'])->findOrEmpty();
					if ($find_send->isEmpty()) {
						$send_data = [
							'user_id' => $project_log['user_id'],
							'money' => array_sum(array_column($send_detail, 'money')),
							'detail' => $send_detail,
							'code' => date('YmdHis') . rand(00000, 99999),
							'send_time' => $dose_value['week'],
							'school_id' => $dose_value['school_id'],
						];

						$send_result = Send::create($send_data);
						$send_result_id = $send_result->id;
					} else {
						$send_detail = array_merge($send_detail, $find_send['detail']);
						$send_data = [
							'user_id' => $project_log['user_id'],
							'money' => array_sum(array_column($send_detail, 'money')),
							'detail' => $send_detail,
							'code' => date('YmdHis') . rand(00000, 99999),
							'send_time' => $dose_value['week'],
							'school_id' => $dose_value['school_id'],
						];

						$send_result = $find_send->save($send_data);
						$send_result_id = $find_send->id;
					}

					if (!empty($offer_details)) {
						$find_offer = OfferDetail::where('school_id', $dose_value['school_id'])->where('send_time', strtotime($dose_value['week']))->findOrEmpty();
						if ($find_offer->isEmpty()) {
							$offer_detail_data = [
								'name' => $dose_value['week'] . '报价单',
								'send_id' => $send_result_id,
								'code' => date('YmdHis') . rand(00000, 99999),
								'money' => array_sum(array_column($offer_details, 'money')),
								'detail' => $offer_details,
								'send_time' => $dose_value['week'],
								'school_id' => $dose_value['school_id'],
							];
							$offer_detail = OfferDetail::create($offer_detail_data);
							$offer_detail_id[] = $offer_detail->id;
							$school_id[] = $dose_value['school_id'];
						} else {
							$offer_details = array_merge($offer_details, $find_offer['detail']);
							$offer_detail_data = [
								'name' => $dose_value['week'] . '报价单',
								'send_id' => $send_result_id,
								'code' => date('YmdHis') . rand(00000, 99999),
								'money' => array_sum(array_column($offer_details, 'money')),
								'detail' => $offer_details,
								'send_time' => $dose_value['week'],
								'school_id' => $dose_value['school_id'],
							];
							$offer_detail = $find_offer->save($offer_detail_data);
							$offer_detail_id[] = $find_offer->id;
							$school_id[] = $dose_value['school_id'];
						}
					}
				}

				if (!empty($send_detail0)) {
					$find_send0 = Send::where('school_id', 0)->where('send_time', strtotime($dose_value['week']))->where('user_id', $project_log['user_id'])->findOrEmpty();
					if ($find_send0->isEmpty()) {
						$send_data0 = [
							'user_id' => $project_log['user_id'],
							'money' => array_sum(array_column($send_detail0, 'money')),
							'detail' => $send_detail0,
							'code' => date('YmdHis') . rand(00000, 99999),
							'send_time' => $dose_value['week'],
							'school_id' => 0,
						];

						$send_result0 = Send::create($send_data0);
						$send_result0_id = $send_result0->id;
					} else {
						$send_detail0 = array_merge($send_detail0, $find_send0['detail']);
						$send_data0 = [
							'user_id' => $project_log['user_id'],
							'money' => array_sum(array_column($send_detail0, 'money')),
							'detail' => $send_detail0,
							'code' => date('YmdHis') . rand(00000, 99999),
							'send_time' => $dose_value['week'],
							'school_id' => 0,
						];

						$send_result0 = $find_send0->save($send_detail0);
						$send_result0_id = $find_send0->id;
					}

					if (!empty($offer_details)) {
						$find_offer = OfferDetail::where('school_id', $dose_value['school_id'])->where('send_time', strtotime($dose_value['week']))->findOrEmpty();
						if ($find_offer->isEmpty()) {
							$offer_detail_data = [
								'name' => $dose_value['week'] . '报价单',
								'send_id' => $send_result0_id,
								'code' => date('YmdHis') . rand(00000, 99999),
								'money' => array_sum(array_column($offer_details, 'money')),
								'detail' => $offer_details,
								'send_time' => $dose_value['week'],
								'school_id' => $dose_value['school_id'],
							];
							$offer_detail = OfferDetail::create($offer_detail_data);
							$offer_detail_id[] = $offer_detail->id;
							$school_id[] = $dose_value['school_id'];
						} else {
							$offer_details = array_merge($offer_details, $find_offer['detail']);
							$offer_detail_data = [
								'name' => $dose_value['week'] . '报价单',
								'send_id' => $send_result0_id,
								'code' => date('YmdHis') . rand(00000, 99999),
								'money' => array_sum(array_column($offer_details, 'money')),
								'detail' => $offer_details,
								'send_time' => $dose_value['week'],
								'school_id' => $dose_value['school_id'],
							];
							$offer_detail = $find_offer->save($offer_detail_data);
							$offer_detail_id[] = $find_offer->id;
							$school_id[] = $dose_value['school_id'];
						}
					}
				}

			}
			$school_id = array_unique($school_id);
			foreach ($school_id as $sk => $sv) {
				$offer_detail_list = OfferDetail::whereIn('id', $offer_detail_id)->where('school_id', $sv)->select()->toArray();
				$filter_detail = array_column($offer_detail_list, 'detail');
				$twoDimArray = [];

				// 遍历三维数组，将其转换为二维数组
				foreach ($filter_detail as $subArray) {
					foreach ($subArray as $item) {
						$twoDimArray[] = $item;
					}
				}

				$filter_detail = $this->array_do($twoDimArray);

				$start = date('Y-m-d', strtotime('next monday'));
				$end = date('Y-m-d', strtotime($start . '+ 6 days'));
				$offer_data = [
					'name' => $start . '-' . $end . '报价单',
					'money' => array_sum(array_column($offer_detail_list, 'money')),
					'detail' => $filter_detail,
					'school_id' => $sv,
				];
				$offer = Offer::create($offer_data);
				$offer_detail_id_list = array_column($offer_detail_list, 'id');
				OfferDetail::whereIn('id', $offer_detail_id_list)->update(['offer_id' => $offer->id]);
			}
		}

	}
	public function array_do3($array1, $array2) {
		$mergedArray = [];

		// Create a map for the first array using type_id as key
		$array1Map = [];
		foreach ($array1 as $item) {
			$typeId = $item['type_id'];
			$array1Map[$typeId] = $item;
		}

		// Merge arrays based on type_id and only keep the merged ones
		foreach ($array2 as $item) {
			$typeId = $item['type_id'];
			if (isset($array1Map[$typeId])) {
				$mergedArray[] = array_merge($array1Map[$typeId], $item);
			}
		}

		return $mergedArray;
	}
	public function array_do($array) {
		$result = [];

		foreach ($array as $item) {
			$type_id = $item['type_id'];
			if (!isset($result[$type_id])) {
				$result[$type_id] = $item;
			} else {
				$result[$type_id]['num'] += $item['num'];
			}
		}

		$result = array_values($result);
		return $result;
	}
	public function array_do2($data) {
		$groupedData = [];

		foreach ($data as $item) {
			$school_id = $item['school_id'];
			$type_id = $item['type_id'];
			$dose_id = $item['dose_id'];
			$brand_id = $item['brand_id'];
			$order_id = $item['order_id'];
			$key = $school_id . '-' . $type_id . '-' . $dose_id;

			if (!isset($groupedData[$key])) {
				$groupedData[$key] = $item;
			}

			$groupedData[$key]['num'] += $item['num'];
		}
		$result = array_values($groupedData);
		return $result;
	}
	public function quest() {
		echo '[计划任务]--开始运行';
		echo "\r\n";
		$quest = Quest::where('id', 1)->findOrEmpty();
		if (!$quest->isEmpty()) {
			if ($quest['status'] == 1) {
				$project_list = Project::whereNotIn('status', [2, 3])->order('end_time', 'asc')->select()->toArray();

				foreach ($project_list as $key => $value) {
					if (time() >= strtotime($value['start_time']) && time() <= strtotime($value['end_time'])) {

						Project::where('id', $value['id'])->update(['status' => 1]);
					}
					if (time() >= strtotime($value['end_time'])) {
						$user_in_list = ProjectLog::where('project_id', $value['id'])->column('user_id'); //已投标用户
						$company_not_in_list = User::whereNotIn('id', $user_in_list)->column('company_id'); //未投标公司
						$param['cate'] = [$value['cate_id']];
						Company::scope('ApiWhere', $param)->whereIn('id', $company_not_in_list)->inc('not_open')->update();
						$lian_open = 1;

						$company_in_list = Company::scope('ApiWhere', $param)->whereIn('id', $company_not_in_list)->select(); //分类未投标公司
						foreach ($company_in_list as $kc => $vc) {
							$project2 = Project::where('cate_id', $value['cate_id'])->where('id', '<', $value['id'])->order('id', 'desc')->findOrEmpty();
							if (!$project2->isEmpty()) {
								$lian_open = 2;
								$project3 = Project::where('cate_id', $value['cate_id'])->where('id', '<', $project2['id'])->order('id', 'desc')->findOrEmpty();
								if (!$project3->isEmpty()) {
									Company::where('id', $vc['id'])->inc('lian_open')->update();
									$company1 = Company::where('id', $vc['id'])->findOrEmpty();
									if ($company1['lian_open'] >= 2) {
										Company::where('id', $vc['id'])->update(['lian_open' => 0]);
									}
									$company2 = Company::where('id', $vc['id'])->findOrEmpty();
									if ($company2['lian_open'] == 0) {
										//User::where('company_id', $vc['id'])->update(['status' => 0]);
										$company = Company::where('id', $vc['id'])->findOrEmpty();
										if (!$company->isEmpty()) {
											$new_cate = array_diff($company['cate'], array($value['cate_id']));
											// 			Company::where('id', $vc['id'])->update(['cate' => implode(',', $new_cate), 'lian_open' => 1]);
										}
									}

								}
							}
						}
						Project::where('id', $value['id'])->update(['status' => 2]);
						$project_log = ProjectLog::where('project_id', $value['id'])->select()->toArray();

						$result = $this->array_sort($project_log, 'all_money');
						// if ($value['win'] == 0) {

						// 	if (isset($result[2]) && $result[1]['all_money'] != $result[2]['all_money']) {
						// 		ProjectLog::where('id', $result[1]['id'])->update(['status' => 2]);
						// 		ProjectLog::where('project_id', $value['id'])->where('id', '<>', $result[1]['id'])->update(['status' => 1]);
						// 		$user = User::where('id', $result[1]['user_id'])->findOrEmpty();
						// 		if (!$user->isEmpty()) {
						// 			$this->send_sms('2039672', [$value['title']], [$user['mobile']]);
						// 			$company = Company::where('id', $user['company_id'])->findOrEmpty();
						// 			if (!$company->isEmpty()) {
						// 				$notice_data = [
						// 					'title' => '恭喜' . $company['company_name'] . '中标',
						// 					'content' => '恭喜' . $company['company_name'] . '中标',
						// 				];
						// 				Notice::create($notice_data);
						// 			}

						// 		}

						// 	} else {
						// 		$project_log_like = ProjectLog::where('project_id', $value['id'])->where('all_money', $result[1]['all_money'])->order('id', 'asc')->select()->toArray();
						// 		ProjectLog::where('id', $project_log_like[0]['id'])->update(['status' => 2]);
						// 		ProjectLog::where('project_id', $value['id'])->where('id', '<>', $project_log_like[0]['id'])->update(['status' => 1]);
						// 		$user = User::where('id', $project_log_like[0]['user_id'])->findOrEmpty();
						// 		if (!$user->isEmpty()) {
						// 			$this->send_sms('2039672', [$value['title']], [$user['mobile']]);
						// 			$company = Company::where('id', $user['company_id'])->findOrEmpty();
						// 			if (!$company->isEmpty()) {
						// 				$notice_data = [
						// 					'title' => '恭喜' . $company['company_name'] . '中标',
						// 					'content' => '恭喜' . $company['company_name'] . '中标',
						// 				];
						// 				Notice::create($notice_data);
						// 			}

						// 		}
						// 		// $mobile = [];
						// 		// foreach ($project_log_like as $lk => $lv) {
						// 		// 	$user = User::where('id', $lv['user_id'])->findOrEmpty();
						// 		// 	if (!$user->isEmpty()) {
						// 		// 		$mobile[] = $user['mobile'];
						// 		// 	}
						// 		// }
						// 		// $this->send_sms('2039667', [$value['title']], $mobile);
						// 	}
						// }
						if ($value['win'] == 0) {

							if (isset($result[1]) && $result[0]['all_money'] != $result[1]['all_money']) {
								ProjectLog::where('id', $result[0]['id'])->update(['status' => 2]);
								ProjectLog::where('project_id', $value['id'])->where('id', '<>', $result[0]['id'])->update(['status' => 1]);
								$user = User::where('id', $result[0]['user_id'])->findOrEmpty();
								if (!$user->isEmpty()) {
									$this->send_sms('2039672', [$value['title']], [$user['mobile']]);
									$company = Company::where('id', $user['company_id'])->findOrEmpty();
									if (!$company->isEmpty()) {
										$notice_data = [
											'title' => '恭喜' . $company['company_name'] . '中标',
											'content' => '恭喜' . $company['company_name'] . '中标',
										];
										Notice::create($notice_data);
									}

								}

							} else {
								if (count($project_log) >= 1) {

									$project_log_like = ProjectLog::where('project_id', $value['id'])->where('all_money', $result[0]['all_money'])->order('id', 'asc')->select()->toArray();
									ProjectLog::where('id', $project_log_like[0]['id'])->update(['status' => 2]);
									ProjectLog::where('project_id', $value['id'])->where('id', '<>', $project_log_like[0]['id'])->update(['status' => 1]);
									$user = User::where('id', $project_log_like[0]['user_id'])->findOrEmpty();
									if (!$user->isEmpty()) {
										$this->send_sms('2039672', [$value['title']], [$user['mobile']]);
										$company = Company::where('id', $user['company_id'])->findOrEmpty();
										if (!$company->isEmpty()) {
											$notice_data = [
												'title' => '恭喜' . $company['company_name'] . '中标',
												'content' => '恭喜' . $company['company_name'] . '中标',
											];
											Notice::create($notice_data);
										}

									}
								}
								// $mobile = [];
								// foreach ($project_log_like as $lk => $lv) {
								// 	$user = User::where('id', $lv['user_id'])->findOrEmpty();
								// 	if (!$user->isEmpty()) {
								// 		$mobile[] = $user['mobile'];
								// 	}
								// }
								// $this->send_sms('2039667', [$value['title']], $mobile);
							}
						}
					}
				}

			}
		}

	}
	function array_sort($arr, $keys, $type = 'asc') {
		$keysvalue = $new_array = array();
		foreach ($arr as $k => $v) {
			$keysvalue[$k] = $v[$keys];
		}
		if ($type == 'asc') {
			asort($keysvalue);
		} else {
			arsort($keysvalue);
		}
		reset($keysvalue);
		foreach ($keysvalue as $k => $v) {
			$new_array[] = $arr[$k];
		}
		return $new_array;
	}
	public function searchsum($arr, $field) {
		if (!is_array($arr) || !$field) {
			return false;
		}

		$temp = array();
		foreach ($arr as $key => $val) {
			$temp[] = $val[$field];
		}

		return array_sum($temp);
	}
	public function send_sms($template_id, $param, $mobile) {
		try {

			$cred = new Credential("AKIDJTP8kHagXEi17zf6PUL4c4KRREmRzLUS", "Ii0BHOSQSPAsRtGUZZP3WwLpIerBTwc8");

			$httpProfile = new HttpProfile();

			$httpProfile->setReqMethod("GET"); // post请求(默认为post请求)
			$httpProfile->setReqTimeout(30); // 请求超时时间，单位为秒(默认60秒)
			$httpProfile->setEndpoint("sms.tencentcloudapi.com"); // 指定接入地域域名(默认就近接入)

			$clientProfile = new ClientProfile();
			$clientProfile->setSignMethod("TC3-HMAC-SHA256"); // 指定签名算法(默认为HmacSHA256)
			$clientProfile->setHttpProfile($httpProfile);

			$client = new SmsClient($cred, "ap-nanjing", $clientProfile);

			// 实例化一个 sms 发送短信请求对象,每个接口都会对应一个request对象。
			$req = new SendSmsRequest();

			/* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId，示例如1400006666 */
			// 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
			$req->SmsSdkAppId = "1400880328";

			$req->SignName = "徐州恒清食品科技有限公司";

			$req->TemplateId = $template_id;

			$req->TemplateParamSet = $param;

			$req->PhoneNumberSet = $mobile;

			$resp = $client->SendSms($req);

			$result = $resp;

		} catch (TencentCloudSDKException $e) {
			echo $e;
		}

	}
	// public function onConnect($connection) {
	// 	$connection->send('连接成功');
	// 	echo "connection-id = {$connection->id}\n";
	// 	echo "new connection from ip " . $connection->id . "\n";
	// }

	// public function onMessage($connection, $data) {
	// 	if (isset($data)) {
	// 		$connection->id = $data;
	// 		$arr = json_decode($data, TRUE);
	// 		// db('user')->where("id", $arr['uid'])->update(['online' => 1]);
	// 		$connection->send($data);
	// 	}
	// }

	// public function onClose($connection) {
	// 	if (is_string($connection->id)) {
	// 		$arr = json_decode($connection->id, TRUE);
	// 		// db('user')->where("id", $arr['uid'])->update(['online' => 0]);
	// 	}
	// 	$connection->close();
	// 	echo "close-id = {$connection->id}\n";
	// }

	// public function onError($connection) //当客户端的连接上发生错误时触发
	// {
	// 	if (is_string($connection->id)) {
	// 		$arr = json_decode($connection->id, TRUE);
	// 		// db('user')->where("id", $arr['uid'])->update(['online' => 0]);
	// 	}
	// 	$connection->close();
	// 	echo "close-id = {$connection->id}\n";
	// }

}
